package com.lichao.tools;

/**
 * @author: li chao
 * @Desc:
 * @create: 2024-11-05 14:39
 **/
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Example {
    public static String encryptMD5(String input) {
        try {
            // 创建MD5加密对象
            MessageDigest md = MessageDigest.getInstance("MD5");
            // 执行加密操作
            byte[] messageDigest = md.digest(input.getBytes());
            // 将字节数组转换为16进制字符串
            StringBuilder hexString = new StringBuilder();
            for (byte b : messageDigest) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }
            // 返回加密后的字符串
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        String input = "password123";
        String encrypted = encryptMD5(input);
        System.out.println("Original: " + input);
        System.out.println("Encrypted: " + encrypted);

        String input1 = "password123";
        String encrypted1 = encryptMD5(input1);
        System.out.println("Original: " + input1);
        System.out.println("Encrypted: " + encrypted1);
    }
}